package longrise.phone.com.bjjt_jyb.compensate;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.VideoView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.FrameworkManager;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerCar;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.FunctionOptions;
import com.luck.picture.lib.model.PictureConfig;
import com.yalantis.ucrop.entity.LocalMedia;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import longrise.phone.com.bjjt_jyb.Activity.HeNanSurfaceViewCameraActivity;
import longrise.phone.com.bjjt_jyb.Activity.MainActivity;
import longrise.phone.com.bjjt_jyb.Activity.MyVideoActivity;
import longrise.phone.com.bjjt_jyb.Adapter.CarLossAdapter;
import longrise.phone.com.bjjt_jyb.Application.BaseApplication;
import longrise.phone.com.bjjt_jyb.Constant.MsgConstant;
import longrise.phone.com.bjjt_jyb.Constant.URLConstant;
import longrise.phone.com.bjjt_jyb.R;
import longrise.phone.com.bjjt_jyb.Utils.CommontUtils;
import longrise.phone.com.bjjt_jyb.Utils.FileUtils;
import longrise.phone.com.bjjt_jyb.Utils.ImageLoaderForSettingUtils;
import longrise.phone.com.bjjt_jyb.Utils.RecordHelper;
import longrise.phone.com.bjjt_jyb.Utils.RecordViewManager;
import longrise.phone.com.bjjt_jyb.Utils.StringUtils;
import longrise.phone.com.bjjt_jyb.Utils.UiUtil;
import longrise.phone.com.bjjt_jyb.Utils.UiUtils;
import longrise.phone.com.bjjt_jyb.widget.PicModule;


/**
 * 上传事故照片界面，Created by Administrator on 2016/5/12.
 */
public class AccidentLoadingPictureView extends LFView implements View.OnClickListener, ILSMsgListener, MainActivity.OnActivityReturnBitmap, ILFMsgListener, AdapterView.OnItemClickListener, RecordViewManager.recordOver {

    private Context context;
    private BaseApplication mApplication;
    private View view;
    private RecordViewManager recordManager;
    private Dialog processDialog;
    private CarLossAdapter adapter;
    private String bImage;
    private String caseNo;
    private String recordPath;
    private String file;
    private int position;
    private int imageType;//标识拍照的类型
    private int imageCount = -1;//上传事故时单车为6双车为8，交警认定上传后要修改这个值的大小
    private boolean videoAlreadyEnter = false;//视频录制过的标志
    private EntityBean[] unqualifylist;
    private EntityBean[] isqualifylist;
    private ArrayList<String> itemsicon = new ArrayList<>();
    private Map<Integer, Integer> takePicOver = new HashMap<>();
    private List<Integer> reLoadingPic;
    private int[] picIdentify;
    private int[] picBackground;
    private int[] takingPicBackground;
    private String[] picText;
    private LinearLayout hn_btn_back_new;
    private TextView tv_chooseifpic;
    private Button bt_load;
    private VideoView vv_video;
    private GridView gv_pic;
    private PicModule pm_carhead;
    private PicModule pm_cartrail;
    private PicModule pm_vedio;
    private PicModule pm_cartouchplace;
    private PicModule pm_carside;
    private PicModule pm_jfidcardfront;
    private PicModule pm_jfidcardback;
    private PicModule pm_yfidcardfront;
    private PicModule pm_yfidcardback;
    private int fromWhere;
    private int takepicKind;
    private PicModule pm_record;
    private LinearLayout ll_video_play_new;
    private Dialog dialog;
    private String kckpUserType;
    private int picType=0;

    /**
     * @param c           context
     * @param caseNo      案件编号
     * @param fromWhere   0是正常的跳转，1是照片审核后跳转来的
     * @param takePicKind 0为单车，1为双车，2为机动车与非机动车，3为纯非机动。之后所有的界面都以此为准
     */
    public AccidentLoadingPictureView(Context c, String caseNo, int fromWhere, int takePicKind) {
        super(c);
        this.context = c;
        this.caseNo = caseNo;
        this.mApplication = (BaseApplication) c.getApplicationContext();
        this.fromWhere = fromWhere;
        this.takepicKind = takePicKind;

    }

    public void setUnqualifylist(EntityBean[] unqualifylist) {
        this.unqualifylist = unqualifylist;
    }

    public void setIsqualifylist(EntityBean[] isqualifylist) {
        this.isqualifylist = isqualifylist;
    }

    @Override
    public FormParameter getFormParameter() {
        return null;
    }

    @Override
    public View getView() {
        return view;
    }

    @Override
    public void init() {
        setShowtitle(false);
        if (context instanceof MainActivity) {
            ((MainActivity) context).setOnActivityReturnBitmap(this);
        }
        if (takepicKind == 0) {
            picIdentify = new int[]{0, 1, 2, 6, 7};
            picBackground = new int[]{R.mipmap.danche001, R.mipmap.danche002, R.mipmap.danche003, R.mipmap.jsz, R.mipmap.xsz};
            takingPicBackground = new int[]{R.mipmap.car_6, R.mipmap.car_7, R.mipmap.car_5, R.mipmap.jsz_4, R.mipmap.xsz_5};
            picText = new String[]{"车头前方照片", "车尾后方照片", "擦碰点照片", "车主驾驶证", "车主行驶证"};
        } else if (takepicKind == 1) {
            picIdentify = new int[]{0, 1, 2, 3, 6, 7, 8, 9};
            picBackground = new int[]{R.mipmap.ctqf, R.mipmap.cwhf, R.mipmap.cpd, R.mipmap.sgcf, R.mipmap.jsz, R.mipmap.xsz, R.mipmap.jsz, R.mipmap.xsz};
            takingPicBackground = new int[]{R.mipmap.car_6, R.mipmap.car_7, R.mipmap.car_5, R.mipmap.car_8, R.mipmap.jsz_4, R.mipmap.xsz_5, R.mipmap.jsz_4, R.mipmap.xsz_5};
            picText = new String[]{"车头前方照片", "车尾后方照片", "擦碰点照片", "事故侧方全景照片", "甲方驾驶证", "甲方行驶证", "乙方驾驶证", "乙方行驶证"};
        } else if (takepicKind == 2) {
            picIdentify = new int[]{0, 1, 2, 3, 6, 7, 18, 19};
            picBackground = new int[]{R.mipmap.sgcf_new1, R.mipmap.cfx_new1, R.mipmap.cpd_new1, R.mipmap.sgcfqj_1, R.mipmap.jsz, R.mipmap.xsz, R.mipmap.sfz_1, R.mipmap.sfz_2};
            takingPicBackground = new int[]{R.mipmap.ctqf_2, R.mipmap.cwh_2, R.mipmap.cpd_2, R.mipmap.sgcfqj_2, R.mipmap.jsz_4, R.mipmap.xsz_5, R.mipmap.sfz_7, R.mipmap.sfz_8};
            picText = new String[]{"车头前方照片", "车尾后方照片", "擦碰点照片", "事故侧方全景照片", "甲方驾驶证", "甲方行驶证", "乙方身份证正面", "乙方身份证反面"};
        } else if (takepicKind == 3) {
            picIdentify = new int[]{0, 1, 2, 3, 16, 17, 18, 19};
            picBackground = new int[]{R.mipmap.ctqfnew11, R.mipmap.cwhfnew1, R.mipmap.cpdnew1, R.mipmap.sgcefnew1, R.mipmap.sfz_1, R.mipmap.sfz_2, R.mipmap.sfz_1, R.mipmap.sfz_2};
            takingPicBackground = new int[]{R.mipmap.ctqfnew12, R.mipmap.cwhfnew2, R.mipmap.cpdnew2, R.mipmap.sgcefnew2, R.mipmap.sfz_7, R.mipmap.sfz_8, R.mipmap.sfz_7, R.mipmap.sfz_8};
            picText = new String[]{"车头前方照片", "车尾后方照片", "擦碰点照片", "事故侧方全景照片", "甲方身份证正面", "甲方身份证反面", "乙方身份证正面", "乙方身份证反面"};
        }
        imageCount = picIdentify.length;
        initOnlyCar();
        if (recordManager == null) {
            recordManager = new RecordViewManager(context, view);
            recordManager.setMyRecordOver(this);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        position = i;
        imageType = 20;
        if (takepicKind == 0) {
            if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(R.id.gv_pic,1);
            else getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.car_8, 1119);
        } else if (takepicKind == 1) {
            if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(R.id.gv_pic,1);
            else getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.car_8, 1119);
        } else if (takepicKind == 2) {
            if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(R.id.gv_pic,1);
            else getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.sgcf_new2, 1119);
        } else if (takepicKind == 3) {
            if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(R.id.gv_pic,1);
            else getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.ctqfnew12, 1119);
        }
    }


    //初始化事故布局及注册事件
    private void initOnlyCar() {
        //view = inflater.inflate(R.layout.view_accidentloadingpicturenew, null);
        //view = LayoutInflater.from(context).inflate(R.layout.viewsinglecaraccidentloadingpic, null);
        if (takepicKind == 0) {
            view = View.inflate(context, R.layout.viewsinglecaraccidentloadingpic, null);
            LinearLayout  ll_takePic = (LinearLayout) view.findViewById(R.id.ll_takePic);
            ll_takePic.setFocusable(true);
            ll_takePic.setFocusableInTouchMode(true);
            ll_takePic.requestFocus();
        } else {
            view = View.inflate(context, R.layout.view_accidentloadingpicture, null);
            pm_jfidcardback = (PicModule) view.findViewById(R.id.pm_jfidcardback);
            pm_yfidcardfront = (PicModule) view.findViewById(R.id.pm_yfidcardfront);
            pm_yfidcardback = (PicModule) view.findViewById(R.id.pm_yfidcardback);
        }
        ll_video_play_new = (LinearLayout) view.findViewById(R.id.ll_video_play_new);
        ScrollView scrollView1_new = (ScrollView) view.findViewById(R.id.sv_scrollView);//将ScrollView初始化到顶部
        scrollView1_new.smoothScrollTo(0, 20);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText("现场拍照");
        tv_chooseifpic = (TextView) view.findViewById(R.id.tv_chooseifpic);
        hn_btn_back_new = (LinearLayout) view.findViewById(R.id.hn_btn_back);
        bt_load = (Button) view.findViewById(R.id.bt_load);
        pm_vedio = (PicModule) view.findViewById(R.id.pm_vedio);
        pm_record = (PicModule) view.findViewById(R.id.pm_record);
        pm_carhead = (PicModule) view.findViewById(R.id.pm_carhead);
        pm_cartrail = (PicModule) view.findViewById(R.id.pm_cartrail);
        pm_cartouchplace = (PicModule) view.findViewById(R.id.pm_cartouchplace);
        pm_carside = (PicModule) view.findViewById(R.id.pm_carside);
        pm_jfidcardfront = (PicModule) view.findViewById(R.id.pm_jfidcardfront);
        if (takepicKind == 0) {
            pm_carhead.setModleParameter(picBackground[0], picText[0]);
            pm_cartrail.setModleParameter(picBackground[1], picText[1]);
            pm_cartouchplace.setModleParameter(picBackground[2], picText[2]);
            pm_carside.setModleParameter(picBackground[3], picText[3]);
            pm_jfidcardfront.setModleParameter(picBackground[4], picText[4]);
        } else {
            pm_carhead.setModleParameter(picBackground[0], picText[0]);
            pm_cartrail.setModleParameter(picBackground[1], picText[1]);
            pm_cartouchplace.setModleParameter(picBackground[2], picText[2]);
            pm_carside.setModleParameter(picBackground[3], picText[3]);
            pm_jfidcardfront.setModleParameter(picBackground[4], picText[4]);
            pm_jfidcardback.setModleParameter(picBackground[5], picText[5]);
            pm_yfidcardfront.setModleParameter(picBackground[6], picText[6]);
            pm_yfidcardback.setModleParameter(picBackground[7], picText[7]);
        }
        gv_pic = (GridView) view.findViewById(R.id.gv_pic);
        adapter = new CarLossAdapter(context, itemsicon);
        gv_pic.setAdapter(adapter);
        kckpUserType = mApplication.getKckpUserType();
        gv_pic.setOnItemClickListener(this);
        regEvent(true);
        if (fromWhere == 1) {
            reTakepic();
        }
    }

    /**
     * 重拍照片
     */
    private void reTakepic() {
        if (takepicKind == 0) pm_record.setVisibility(View.INVISIBLE);
        ll_video_play_new.setVisibility(View.GONE);
        tv_chooseifpic.setVisibility(View.GONE);
        gv_pic.setVisibility(View.GONE); //将选拍和视频的ui隐藏
        if (null != isqualifylist) {
            for (EntityBean element : isqualifylist) {
                String imagetype = (String) element.get("imagetype");
                String imageurl = (String) element.get("imageurl");
                int imagetypeInt = Integer.parseInt(imagetype);
                if (picIdentify[0] == imagetypeInt) {
                    ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_carhead.getIv_pic());
                } else if (picIdentify[1] == imagetypeInt) {
                    ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_cartrail.getIv_pic());
                } else if (picIdentify[2] == imagetypeInt) {
                    ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_cartouchplace.getIv_pic());
                } else if (picIdentify[3] == imagetypeInt) {
                    ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_carside.getIv_pic());
                } else if (picIdentify[4] == imagetypeInt) {
                    ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_jfidcardfront.getIv_pic());
                }
                if (takepicKind != 0) {
                    if (picIdentify[5] == imagetypeInt) {
                        ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_jfidcardback.getIv_pic());
                    } else if (picIdentify[6] == imagetypeInt) {
                        ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_yfidcardfront.getIv_pic());
                    } else if (picIdentify[7] == imagetypeInt) {
                        ImageLoaderForSettingUtils.getInstance(context).display(imageurl, pm_yfidcardback.getIv_pic());
                    }
                }
            }
        }
        //将不成功的照片设置传输失败，提示重拍
        setImageView();
    }


    /**
     * 根据，获取回来的失败的imagetype，初始化重新拍照
     */
    private void setImageView() {
        reLoadingPic = new ArrayList<>();//不成功的照片imagetype集合
        imageCount = unqualifylist.length;
        for (EntityBean element : unqualifylist) {
            int imagetype = (int) element.get("imagetype");
            reLoadingPic.add(imagetype);
        }
    }

    private void regEvent(boolean b) {
        if (hn_btn_back_new != null) {
            hn_btn_back_new.setOnClickListener(b ? this : null);
        }
        if (bt_load != null) {
            bt_load.setOnClickListener(b ? this : null);
        }
        if (pm_vedio != null) {
            pm_vedio.setOnClickListener(b ? this : null);
        }
        if (pm_carhead != null) {
            pm_carhead.setOnClickListener(b ? this : null);
        }
        if (pm_cartrail != null) {
            pm_cartrail.setOnClickListener(b ? this : null);
        }
        if (pm_cartouchplace != null) {
            pm_cartouchplace.setOnClickListener(b ? this : null);
        }
        if (pm_carside != null) {
            pm_carside.setOnClickListener(b ? this : null);
        }
        if (pm_jfidcardfront != null) {
            pm_jfidcardfront.setOnClickListener(b ? this : null);
        }
        if (pm_jfidcardback != null) {
            pm_jfidcardback.setOnClickListener(b ? this : null);
        }
        if (pm_yfidcardfront != null) {
            pm_yfidcardfront.setOnClickListener(b ? this : null);
        }
        if (pm_yfidcardback != null) {
            pm_yfidcardback.setOnClickListener(b ? this : null);
        }
        if (b) {
            this.addILSMsgListener(this);
            this.addILFMsgListener(this);
        } else {
            this.removeILSMsgListener(this);
            this.removeILFMsgListener(this);
        }
    }

    @Override
    public void refresh() {

    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void onClick(View v) {
        OnlyCarClick(v.getId());
    }

    //点击拍照事件
    private void OnlyCarClick(int Rid) {
        switch (Rid) {
            case R.id.pm_carhead:
                if (ifalreadyPic(picIdentify[0])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[0], "(请确保道路标线在拍摄画面中。)", takingPicBackground[0]);
                break;
            case R.id.pm_cartrail:
                if (ifalreadyPic(picIdentify[1])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[1], "(请确保道路标线在拍摄画面中。)", takingPicBackground[1]);
                break;
            case R.id.pm_cartouchplace:
                if (ifalreadyPic(picIdentify[2])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[2], null, takingPicBackground[2]);
                break;
            case R.id.pm_carside:
                if (ifalreadyPic(picIdentify[3])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[3], null, takingPicBackground[3]);
                break;
            case R.id.pm_jfidcardfront:
                if (ifalreadyPic(picIdentify[4])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[4], null, takingPicBackground[4]);
                break;
            case R.id.pm_jfidcardback:
                if (ifalreadyPic(picIdentify[5])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[5], null, takingPicBackground[5]);
                break;
            case R.id.pm_yfidcardfront:
                if (ifalreadyPic(picIdentify[6])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[6], null, takingPicBackground[6]);
                break;
            case R.id.pm_yfidcardback:
                if (ifalreadyPic(picIdentify[7])) return;
                if (null != kckpUserType && "9".equals(kckpUserType)) showSelPicDialog(Rid,0);
                else getCamera(picText[7], null, takingPicBackground[7]);
                break;
            case R.id.pm_vedio:
                enterVideo();
                break;
            case R.id.bt_load:
                if (checkTakePhoto()) {
                    if (fromWhere != 1 && null == recordPath) {
                        UiUtil.showToast(getContext(), "请完成录音...");
                        return;
                    }
                    showNext();
                } else {
                    UiUtil.showToast(getContext(), "请您拍摄完照片后进行下一步");
                }
                break;
            case R.id.hn_btn_back:
                showHomeView();
                break;
        }
    }

    /**
     * 判断是否需要重拍
     *
     * @param i 重拍的type
     */
    private Boolean ifalreadyPic(int i) {
        if (null != reLoadingPic && (!reLoadingPic.contains(i))) {//不需要重传，谈toast
            UiUtil.showToast(context, "本张照片已经审核通过，不需要重新拍摄！");
            return true;
        } else {
            imageType = i;
            return false;
        }
    }

    /**
     * 取证完成验证是不是8张
     */
    private boolean checkTakePhoto() {
        return takePicOver.size() == imageCount;
    }

    private void getCamera(String title, String titleBottom, int resourceId) {
        this.getCamera(title, titleBottom, resourceId, -1);
    }

    /**
     * 启动相机
     *
     * @param title       顶部
     * @param titleBottom 底部
     * @param resourceId  背景
     * @param returnCode  返回的标识
     */
    private void getCamera(String title, String titleBottom, int resourceId, int returnCode) {

        Intent intent = new Intent(getContext(), HeNanSurfaceViewCameraActivity.class);
        Bundle bundle = new Bundle();

        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        if (!StringUtils.isEmpty(titleBottom)) {
            bundle.putString("titleBottom", titleBottom);
        }
        if (resourceId != 0) {
            bundle.putInt("backGroundResourceId", resourceId);
        }
        intent.putExtras(bundle);
        if (returnCode == -1) {
            if (context instanceof MainActivity) {
                ((MainActivity) context).startActivityForResult(intent, 110);
            }
        } else {
            if (context instanceof MainActivity) {
                ((MainActivity) context).startActivityForResult(intent, returnCode);
            }
        }
    }

    /**
     * 进入视频录制界面
     */
    private void enterVideo() {
        //进入拍摄视频的界面
        Intent intent = new Intent(getContext(), MyVideoActivity.class);
        if (context instanceof MainActivity) {
            ((MainActivity) context).startActivityForResult(intent, 1110);
        }
    }

    /**
     * 为上传照片
     */
    private void uploadImgInfo(int currentImageType) {
        processDialog = UiUtil.showProcessDialog(getContext(), "正在上传");
        Bitmap bitmap = BitmapFactory.decodeFile(bImage);
        EntityBean bean = new EntityBean();
        bean.set("appcaseno", caseNo);
        bean.set("imagelon", mApplication.getLongitude());
        bean.set("imagelat", mApplication.getLatitude());
        bean.set("imageaddress", mApplication.getAddress());
        bean.set("imageurl", CommontUtils.Bitmap2Bytes(bitmap));
        bean.set("imagebig", CommontUtils.getBitmapSize(bitmap));
        bean.set("imagewide", bitmap.getWidth());
        bean.set("imageheigth", bitmap.getHeight());
        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        String phoneNumber = userinfo.getString("mobilephone");
        if (!StringUtils.isEmpty(phoneNumber)) {
            bean.set("casetelephoe", "");
        }
        //拍照类型
        bean.set("shoottype", "1");//1是定责照片，2是定损照片
        bean.set("imagetype", currentImageType);
        bean.set("imagedate", CommontUtils.getNowTime());
        bean.set("areaid", mApplication.getAreaid());
        bean.set("username", mApplication.getKckpName());
        bean.set("token", mApplication.getToken());
        LoadDataManagerCar.getInstance(context).callService(null, mApplication.getServerUrl(), URLConstant.JJAPPZDSUBMITCASEIMAGE, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (result != null) {
                    if (null != processDialog) {
                        if (processDialog.isShowing()) {//消失不会显示进度
                            processDialog.dismiss();
                        }
                    }
                    EntityBean bean = (EntityBean) result;
                    String restate = bean.getString("restate");
                    String redes = bean.getString("redes");
                    if ("1".equals(restate)) {
                        if (imageType == 20) {
                            adapter.notifyDataSetChanged();
                        } else {
                            setPicToView();//显示照片到相应的位置
                            Integer integer = takePicOver.get(imageType);
                            if (integer != null) {
                                takePicOver.remove(integer);
                            }
                            takePicOver.put(imageType, imageType);
                        }
                        pictureRecognition();
                    } else {
                        showsingle(context, redes);
                    }
                }
            }

            @Override
            public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {//消失不会显示进度
                        processDialog.dismiss();
                    }
                }
                UiUtil.showToast(context, "连接超时，请检查网络后重试。");
            }

            @Override
            public void onFinished(String key, String service) {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {//消失不会显示进度
                        processDialog.dismiss();
                    }
                }
            }
        });
    }


    private void showsingle(final Context context, String redes) {
        UiUtils.showSingleDialog(context, R.mipmap.a_32, redes, "确认", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeAllForm();
                OnDestroy();
                HomePageView homepageview = new HomePageView(context);
                FrameworkManager.getInstance().showNewForm(context, homepageview);
            }
        });
    }

    @Override
    public Object onLSMsg(int code, Object... arg1) {
        switch (code) {
            case MsgConstant.FINSHTAKEPHOTO:
                closeForm();
                OnDestroy();
                break;

            default:
                break;
        }
        return null;
    }

    private PictureConfig.OnSelectResultCallback resultCallback = new PictureConfig.OnSelectResultCallback() {


        @Override
        public void onSelectSuccess(List<LocalMedia> list) {

        }

        @Override
        public void onSelectSuccess(LocalMedia media) {
            String oldbImage = media.getCompressPath();
            bImage = CommontUtils.bitmapNewWaH(oldbImage, context);
            if (bImage == null) return;
            if(picType==1){
                if (itemsicon.size() < 3) {
                    itemsicon.add(position, bImage);
                } else {
                    itemsicon.remove(position);
                    itemsicon.add(position, bImage);
                }
            }
            uploadImgInfo(imageType);
            if (videoAlreadyEnter) {
                playVideo();
            }
        }
    };

    @Override
    public void activityReturnBitmap(int requestCode, int resultCode,
                                     Intent data) {
        if (resultCode == MainActivity.RESULT_OK) {
            if (requestCode == 110) {//照片
                Bundle bundle = data.getExtras();
                bImage = bundle.getString("image");
                if (bImage == null) {
                    return;
                }
                uploadImgInfo(imageType);
                if (videoAlreadyEnter) {
                    playVideo();
                }
            } else if (requestCode == 1110) {//视频
                Bundle bundle = data.getExtras();
                file = bundle.getString("file");
                if (file == null) {
                    return;
                }
                uploadFile();
            } else if (requestCode == 1119) {//其他照片
                Bundle bundle = data.getExtras();//gradview拍摄返回的界面
                bImage = bundle.getString("image");
                if (bImage == null) {
                    return;
                }
                if (itemsicon.size() < 3) {
                    itemsicon.add(position, bImage);
                } else {
                    itemsicon.remove(position);
                    itemsicon.add(position, bImage);
                }
                uploadImgInfo(imageType);
                if (videoAlreadyEnter) {
                    playVideo();
                }
            }
        }
    }

    /**
     * 上传视频
     */
    private void uploadFile() {
        Bitmap videoBitmap = CommontUtils.getVideoBitmap(file);
        if (null == videoBitmap) {
            UiUtil.showToast(context, "视频文件获取失败，请重新录制");
            return;
        }
        processDialog = UiUtil.showProcessDialog(context, "联网中...");
        EntityBean bean = new EntityBean();
        bean.set("appcaseno", caseNo);
        bean.set("imagelon", mApplication.getLongitude());
        bean.set("imagelat", mApplication.getLatitude());
        bean.set("imageaddress", mApplication.getAddress());
        bean.set("imageurl", CommontUtils.encodeBase64File(file));//视频转化的字符串
        bean.set("imagebig", CommontUtils.getBitmapSize(videoBitmap));//视频第一帧图片的大小
        bean.set("imagewide", videoBitmap.getWidth());//视频第一帧图片的宽度
        bean.set("imageheigth", videoBitmap.getHeight());//视频第一帧图片的高度
        EntityBean userinfo = mApplication.getLoginInfo().getBean("userinfo");
        String phoneNumber = userinfo.getString("mobilephone");
        if (!StringUtils.isEmpty(phoneNumber)) {
            bean.set("casetelephoe", "");
        }
        //拍照类型
        bean.set("shoottype", "");//1是定责照片，2是定损照片，3是
        bean.set("imagetype", "13");//13标识视频
        bean.set("imagedate", CommontUtils.getNowTime());
        //bean.set("areaid", "410101000000000000");
        bean.set("areaid", mApplication.getAreaid());
        bean.set("videopicurl", CommontUtils.Bitmap2Bytes(videoBitmap));//视频的第一帧图像的字符串

        LoadDataManagerCar.getInstance(context).callService(null, mApplication.getServerUrl(), URLConstant.KCKPSAVEVIDEOINFO, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (result != null) {
                    if (null != processDialog) {
                        if (processDialog.isShowing()) {//消失不会显示进度
                            processDialog.dismiss();
                        }
                    }
                    EntityBean bean = (EntityBean) result;
                    String restate = bean.getString("restate");
                    String redes = bean.getString("redes");
                    if ("1".equals(restate)) {
                        //视频传输成功,播放视频
                        videoAlreadyEnter = true;
                        playVideo();
                    } else {
                        UiUtil.showToast(context, redes);
                    }
                }
            }

            @Override
            public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {//消失不会显示进度
                        processDialog.dismiss();
                    }
                }
                UiUtil.showToast(context, "连接超时，请检查网络后重试。");
            }

            @Override
            public void onFinished(String key, String service) {
                if (null != processDialog) {
                    if (processDialog.isShowing()) {//消失不会显示进度
                        processDialog.dismiss();
                    }
                }
            }
        });
    }

    /**
     * 判断将图片显示在哪里
     */
    private void setPicToView() {
        if (imageType == picIdentify[0]) {
            pm_carhead.setModuleBackground(bImage);
        } else if (imageType == picIdentify[1]) {
            pm_cartrail.setModuleBackground(bImage);
        } else if (imageType == picIdentify[2]) {
            pm_cartouchplace.setModuleBackground(bImage);
        } else if (imageType == picIdentify[3]) {
            pm_carside.setModuleBackground(bImage);
        } else if (imageType == picIdentify[4]) {
            pm_jfidcardfront.setModuleBackground(bImage);
        } else if (imageType == picIdentify[5]) {
            pm_jfidcardback.setModuleBackground(bImage);
        } else if (imageType == picIdentify[6]) {
            pm_yfidcardfront.setModuleBackground(bImage);
        } else if (imageType == picIdentify[7]) {
            pm_yfidcardback.setModuleBackground(bImage);
        }
    }

    /**
     * 播放视频
     */
    private void playVideo() {
        vv_video = pm_vedio.getVv_video();
        vv_video.setBackgroundResource(0);//去掉背景
        vv_video.setVideoPath(file);
        //设置全屏播放
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(165, 99);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        vv_video.setLayoutParams(layoutParams);
        vv_video.resume();
        vv_video.start();
        vv_video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //播放结束后的动作
                vv_video.resume();
                vv_video.start();
            }
        });
    }


    @Override
    public void OnDestroy() {
        super.OnDestroy();
        regEvent(false);
        RecordHelper recordHelper = RecordHelper.getInstance(context);
        recordHelper.stopMPlayer();
        if (recordManager != null) {
            recordManager.setMyRecordOver(null);
        }
        removeILSMsgListener(this);
        removeILFMsgListener(this);
        view = null;
        if (null != vv_video) {
            vv_video.stopPlayback();
            vv_video = null;
        }
        if (null != dialog) {
            dialog = null;
        }
        closeForm() ;//测试
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {//点击返回按键
            showHomeView();
        }
        return false;
    }

    /**
     * 提示是否不继续处理，返回首页
     */
    private void showHomeView() {
        UiUtils.showDialog(context, null, null, "是否结束本次快处", "返回", "确认",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        closeAllForm();
                        OnDestroy();
                        HomePageView homepageview = new HomePageView(context);
                        FrameworkManager.getInstance().showNewForm(context, homepageview);
                    }
                });
    }

    /**
     * 判断是否是交警账号，进入下个页面
     */
    private void enterNext() {
        try {
            processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
            EntityBean bean = new EntityBean();
            bean.set("appcaseno", caseNo);
            bean.set("data", "2");
            bean.set("issingle", "2");
            LoadDataManagerCar.getInstance(context).callService(null,
                    mApplication.getServerUrl(), URLConstant.JJAPPUPLOADIMGISOVER, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                            if (null != processDialog) {
                                if (processDialog.isShowing()) {
                                    processDialog.dismiss();
                                }
                            }
                            EntityBean bean = (EntityBean) result;
                            String restate = bean.getString("restate");
                            if ("1".equals(restate)) {
                                //删除拍照的文件夹
                                String dir = FileUtils.getDir("KCKP", context);
                                FileUtils.DeleteFolder(dir);
                                String userType = mApplication.getKckpUserType();
                                if (null != userType && "9".equals(userType)) {
                                    if (takepicKind == 0) {
                                        AccidentLoadingView singleaccidentloadingview = new AccidentLoadingView(context, caseNo);
                                        FrameworkManager.getInstance().showNewForm(context, singleaccidentloadingview);
                                    } else {
                                        SelectAccidentView selectaccidentview = new SelectAccidentView(context, caseNo, takepicKind);
                                        FrameworkManager.getInstance().showNewForm(context, selectaccidentview);
                                    }
                                } else {
                                    //进入事故审核页面
                                    AccidentCheckView accidentcheckview;
                                    if (takepicKind == 0 || takepicKind == 1) {
                                        accidentcheckview = new AccidentCheckView(context, caseNo, 0);
                                    } else {
                                        accidentcheckview = new AccidentCheckView(context, caseNo, 1);
                                    }
                                    FrameworkManager.getInstance().showNewForm(context, accidentcheckview);
                                }
                                OnDestroy();
                            } else {
                                UiUtil.showToast(context, "照片传输异常");
                            }
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                            if (null != processDialog) {
                                if (processDialog.isShowing()) {
                                    processDialog.dismiss();
                                }
                            }
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        }

                        @Override
                        public void onFinished(String key, String service) {
                            if (null != processDialog) {
                                if (processDialog.isShowing()) {
                                    processDialog.dismiss();
                                }
                            }
                        }
                    });
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    /**
     * 发送录音文件到后台
     */
    private void sendRecord() {
        try {
            recordPath = recordManager.getRecordPath();
            processDialog = UiUtil.showProcessDialog(context, "加载数据中...");
            EntityBean bean = new EntityBean();
            bean.set("appcaseno", caseNo);
            if (null == recordPath) {
                bean.set("voiceurl", "");
            } else {
                bean.set("voiceurl", CommontUtils.encodeBase64File(recordPath));
            }
            bean.set("imagelon", mApplication.getLongitude());
            bean.set("imagelat", mApplication.getLatitude());
            bean.set("imageaddress", mApplication.getAddress());
            bean.set("areaid", mApplication.getAreaid());
            LoadDataManagerCar.getInstance(context).callService(null,
                    mApplication.getServerUrl(), URLConstant.JJAPPKCKPSAVEVOICEINFO, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                            if (null != processDialog) {
                                if (processDialog.isShowing()) {
                                    processDialog.dismiss();
                                }
                            }
                            EntityBean bean = (EntityBean) result;
                            String restate = bean.getString("restate");
                            if (!"1".equals(restate)) UiUtil.showToast(context, "录音文件发送失败，请重新发送");
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                            if (null != processDialog) {
                                if (processDialog.isShowing()) {
                                    processDialog.dismiss();
                                }
                            }
                            UiUtil.showToast(context, "连接超时，请检查网络后重试。");
                        }

                        @Override
                        public void onFinished(String key, String service) {
                            if (null != processDialog) {
                                if (processDialog.isShowing()) {
                                    processDialog.dismiss();
                                }
                            }
                        }
                    });
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    @Override
    public void onRecordOver() {
        sendRecord();
    }

    // 调取照片识别的接口
    private void pictureRecognition() {
        try {
            EntityBean bean = new EntityBean();
            String userName = mApplication.getLoginInfo().getBean("userinfo")
                    .getString("userflag");
            bean.set("appcaseno", caseNo);
            bean.set("userflag", userName);
            bean.set("token", mApplication.getToken());
            LoadDataManagerCar instance = LoadDataManagerCar.getInstance(context);
            instance.setSoTimeOut(60000);
            instance.setConnectTimeOut(60000);
            instance.callService(null,
                    mApplication.getServerUrl(), URLConstant.JJAPPOCR, bean, new LoadDataManagerFather.OnRequestCompleteListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                        }

                        @Override
                        public void onFinished(String key, String service) {
                        }
                    });
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    //弹出照片上传正常的dialog
    private void showNext() {
        //弹出照片上传正常的dialog
        UiUtils.showDialog(context, null, null, "事故照片上传成功，请进入下一步。", "返回", "确认",
                new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        enterNext();
                    }
                });
    }

    /**
     * 拍照还是从相册
     * @param id 控件的id
     * @param type 0为普通照片，1为其他照片
     */
    private void showSelPicDialog(final int id,final int type) {
        picType =type;
        final FunctionOptions options = new FunctionOptions.Builder()
                .setType(FunctionConfig.TYPE_IMAGE) // 图片or视频 FunctionConfig.TYPE_IMAGE  TYPE_VIDEO
                .setCompress(true) //是否压缩
                .setEnablePixelCompress(true) //是否启用像素压缩
                .setEnableQualityCompress(true) //是否启质量压缩
                .setMaxSelectNum(1) // 可选择图片的数量
                .setMinSelectNum(0)// 图片或视频最低选择数量，默认代表无限制
                .setSelectMode(FunctionConfig.MODE_SINGLE) // 单选 or 多选
                .setShowCamera(false) //是否显示拍照选项 这里自动根据type 启动拍照或录视频
                .setEnablePreview(true) // 是否打开预览选项
                .setEnableCrop(false) // 是否打开剪切选项
                .setPreviewVideo(false) // 是否预览视频(播放) mode or 多选有效
                .setGif(false)// 是否显示gif图片，默认不显示
                .setCheckNumMode(true) //QQ选择风格
                .setImageSpanCount(2) // 每行个数
                .setCompressFlag(2) // 1 系统自带压缩 2 luban压缩
                .create();

        View view = LayoutInflater.from(context).inflate(
                R.layout.change_headportrait, null);
        if (null == view) {
            return;
        }
        Button changetakephoto = (Button) view
                .findViewById(R.id.changetakephoto);
        Button changefrom_album = (Button) view
                .findViewById(R.id.changefrom_album);
        Button changenagative = (Button) view
                .findViewById(R.id.changenagative);
        changetakephoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (id) {
                    case R.id.pm_carhead:
                        getCamera(picText[0], "(请确保道路标线在拍摄画面中。)", takingPicBackground[0]);
                        break;
                    case R.id.pm_cartrail:
                        getCamera(picText[1], "(请确保道路标线在拍摄画面中。)", takingPicBackground[1]);
                        break;
                    case R.id.pm_cartouchplace:
                        getCamera(picText[2], null, takingPicBackground[2]);
                        break;
                    case R.id.pm_carside:
                        getCamera(picText[3], null, takingPicBackground[3]);
                        break;
                    case R.id.pm_jfidcardfront:
                        getCamera(picText[4], null, takingPicBackground[4]);
                        break;
                    case R.id.pm_jfidcardback:
                        getCamera(picText[5], null, takingPicBackground[5]);
                        break;
                    case R.id.pm_yfidcardfront:
                        getCamera(picText[6], null, takingPicBackground[6]);
                        break;
                    case R.id.pm_yfidcardback:
                        getCamera(picText[7], null, takingPicBackground[7]);
                        break;
                    case R.id.gv_pic:
                        if (takepicKind == 0) {
                            getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.car_8, 1119);
                        } else if (takepicKind == 1) {
                             getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.car_8, 1119);
                        } else if (takepicKind == 2) {
                            getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.sgcf_new2, 1119);
                        } else if (takepicKind == 3) {
                            getCamera("其他现场照片", "(请确保道路标线在拍摄画面中。)", R.mipmap.ctqfnew12, 1119);
                        }
                        break;
                }
                dialog.dismiss();
            }
        });
        changefrom_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (context instanceof MainActivity) {
                    PictureConfig.getInstance().init(options).openPhoto((MainActivity) context, resultCallback);
                }
                dialog.dismiss();
            }
        });
        changenagative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(context, R.style.AlertDialogStyle);
        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        dialogWindow.setGravity((Gravity.BOTTOM));
        p.width = WindowManager.LayoutParams.MATCH_PARENT;
        p.height = WindowManager.LayoutParams.WRAP_CONTENT;
       /* WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        p.height = (int) (display.getHeight() * 0.4);
        p.width = (int) (display.getWidth() * 0.8);*/
        dialogWindow.setAttributes(p);
        dialog.show();
    }

}
